#include "threadPool.h"
typedef struct train_s {
    int length;
    char data[1000];
} train_t;

int transFile(int netfd,char *buf){
    //train_t train = {5, "file1"};
    train_t train;
    train.length = strlen(buf) + 1;
    //tesst
    printf("transFile(filename)-----buf=%s \n",buf);
    
    memcpy(train.data, buf, train.length);
    

    printf("transFile(filename)-----train.data=%s \n",train.data);
    
    //train_t train = {strlen(buf),buf};
    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);// 发文件的名字
    
    //int fd = open("file1", O_RDWR);
    int fd = open(buf,O_RDWR);
    
    struct stat statbuf;
    fstat(fd,&statbuf);
    train.length = sizeof(statbuf.st_size);
    memcpy(train.data,&statbuf.st_size,train.length);
    
    printf("transFile(filesize)-----train.data=%ld \n",statbuf.st_size);
    
    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);// 发文件的大小
    char *p = (char *)mmap(NULL,statbuf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    ERROR_CHECK(p,MAP_FAILED,"mmap");

    off_t totalsize = 0;//记录已经发送的长度
    while(totalsize < statbuf.st_size){
        if(statbuf.st_size - totalsize > 1000){
            train.length = 1000;//剩余未发送的内容超过1000
        }
        else{
            train.length = statbuf.st_size - totalsize;
            //剩余内容不足1000
        }
        send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);//发火车头
        
        send(netfd,p+totalsize,train.length,MSG_NOSIGNAL);//火车车厢在mmap映射区
        
        printf("发送文件内容：%s",p+totalsize);
        totalsize += train.length;
    }
    // 补发一个空火车
    train.length = 0;
    printf("transFile End!\n");
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);//发火车头
    munmap(p,statbuf.st_size);
    close(fd);
    return 0;
}
